// @Author EthanScriptOn
// @Desc
package background

import (
	"gitee.com/fatzeng/srf_switch/config"
	"gitee.com/fatzeng/srf_switch_basic_components/switch_log"
	"gitee.com/fatzeng/srf_switch_client_demo/common"
	"gitee.com/fatzeng/srf_switch_client_demo/common/operator_define/mysql_define"
	"gitee.com/fatzeng/srf_switch_stream_bridge/bridge"
)

var AdaptationExecutorMappingRelationship = make(map[bridge.Group]*common.ExecutionElement)

func OperatorStart() error {
	common.Initialization()
	cacheAdaptationConfig()

	for group, element := range AdaptationExecutorMappingRelationship {
		if element == nil {
			continue
		}
		go func(elementBack *common.ExecutionElement, groupBack bridge.Group) {
			err := elementBack.Executor.Execute(elementBack.Ctx)
			if err != nil {
				switch_log.Logger().Error("group: %s, err: %s", groupBack, err)
				return
			}
			response, hasResponse := elementBack.Ctx.GetResponse(mysql_define.MYSQL_BACKGROUND_BRIDGE_CONFIG)
			if !hasResponse {
				switch_log.Logger().Error("group: %s, err: %s", groupBack, err)
			}
			switch_log.Logger().Info("group: %s, response: %s", groupBack, response)
		}(element, group)
	}
	//responseChan := response.(chan interface{})
	//select {
	//case res, ok := <-responseChan:
	//	if ok {
	//		switch_log.Logger().Info("result: ", res)
	//	} else {
	//		switch_log.Logger().Info("chan is closed")
	//	}
	//}
	return nil
}

func cacheAdaptationConfig() {
	env := config.SrfSwitchGlobalConfig.SrfEnvConfig.SrfEnv
	namespace := config.SrfSwitchGlobalConfig.SrfLocatorConfig.SrfNamespace
	group := config.SrfSwitchGlobalConfig.SrfLocatorConfig.SrfGroup
	bridgeConfigs := make([]*bridge.BridgeConfig, 0)
	bridgeGroup := bridge.Group{Env: env, NameSpace: namespace, Group: group}
	element, ok := common.ExecutorMappingRelationship[common.CONSUMER][bridgeGroup]
	if !ok {
		return
	}
	for _, bridgeConfig := range config.SrfSwitchGlobalConfig.SrfBridgeConfig {
		if bridgeConfig.SrfDsUniqueness == "" {
			continue
		}
		response, hasResponse := element.Ctx.GetAdaptationBridgeConfig(bridgeConfig.SrfDsUniqueness)
		if !hasResponse {
			continue
		}
		bridgeConfigs = append(bridgeConfigs, response...)
		if len(bridgeConfigs) <= 0 {
			continue
		}
		clone := element.Ctx.ShallowClone()
		clone.SetGroupConfig(&bridge.GroupConfig{
			Group:         &bridgeGroup,
			BridgeConfigs: bridgeConfigs,
		})
		AdaptationExecutorMappingRelationship[bridgeGroup] = &common.ExecutionElement{
			Executor: element.Executor,
			Ctx:      clone,
		}
	}
}
